package RC4;

import java.io.*;

/**
 * @创建人 MBY381
 * @创建时间 2022/5/15 09:56
 * @描述 暂无
 */
public class RC4Utils {

    private static final String KEY = "xxlssb";

    public static void main(String[] args) throws IOException {
        String original = "mby381zzq227love";
        String str = HLoveyRC4(original, KEY);
        System.out.println("原文：" + original + "\n密文：" + str + "\n还原：" + HLoveyRC4(str, KEY)+"\n");


        fileProcess("D:\\CG\\JAVA\\零碎小项目\\CyberSecurityRC4\\src\\src\\RC4\\mby.txt");



    }


    public static void fileProcess(String fileName) throws IOException {

        FileReader fileReader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        System.out.println("源文件字符集：" + fileReader.getEncoding());

        //新文件处理
        File newFile = new File("D:\\CG\\JAVA\\零碎小项目\\CyberSecurityRC4\\src\\src\\RC4\\output+"+String.valueOf(System.currentTimeMillis()).substring(7)+".txt" );
        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(newFile);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        String line = bufferedReader.readLine();
        while (line != null) {
            System.out.println("读取一行："+line);
            try  {
                bufferedWriter.write(HLoveyRC4(line,KEY)+"\n");
                System.out.println("加密写入成功");
                bufferedWriter.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            line = bufferedReader.readLine();
        }

        bufferedReader.close();
        fileReader.close();
        fileWriter.close();
        bufferedWriter.close();
    }


    public static String HLoveyRC4(String input, String key) {

        int[] vectorS = new int[256];
        byte[] vectorK = new byte[256];

        for (int i = 0; i < 256; i++) {
            vectorS[i] = i;
        }

        for (short i = 0; i < 256; i++) {
            vectorK[i] = (byte) key.charAt((i % key.length()));
        }

        int p = 0;

        for (int i = 0; i < 255; i++) {
            p = (p + vectorS[i] + vectorK[i]) % 256;
            int temp = vectorS[i];
            vectorS[i] = vectorS[p];
            vectorS[p] = temp;
        }


        int i = 0;
        int j = 0;
        char[] inputCharacters = input.toCharArray();
        char[] outputCharacters = new char[inputCharacters.length];
        for (short x = 0; x < inputCharacters.length; x++) {
            i = (i + 1) % 256;
            j = (j + vectorS[i]) % 256;
            int temp = vectorS[i];
            vectorS[i] = vectorS[j];
            vectorS[j] = temp;
            int t = (vectorS[i] + (vectorS[j] % 256)) % 256;
            int iY = vectorS[t];
            char iCY = (char) iY;
            outputCharacters[x] = (char) (inputCharacters[x] ^ iCY);
        }

        return new String(outputCharacters);

    }
}
